import { App, Config, Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core'; // 使用 cool-midway 的 BaseService
import { InjectDataSource, InjectEntityModel } from '@midwayjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { GoodsInfoEntity } from '../entity/info'; // 引入更新后的商品实体
import { GoodsBatchEntity } from '../entity/batch.entity'; // <-- 导入 GoodsBatchEntity
import { GoodsTypeEntity } from '../entity/type'; // <-- 导入 GoodsTypeEntity
import * as oracledb from 'oracledb';
import { IMidwayApplication } from '@midwayjs/core';
import { ILogger } from '@midwayjs/logger';
import { OracleService } from '../../../comm/service/oracle.service'; // 引入 Oracle 服务
import { TrimUtil } from '../../../comm/service/trim.util';

@Provide()
export class GoodsSyncDataService extends BaseService {
  @InjectEntityModel(GoodsInfoEntity) // 注入商品实体模型
  goodsInfoEntity: Repository<GoodsInfoEntity>;

  @InjectEntityModel(GoodsBatchEntity) // <-- 注入 GoodsBatchEntity Repository
  goodsBatchEntity: Repository<GoodsBatchEntity>;

  @InjectEntityModel(GoodsTypeEntity) // <-- 注入 GoodsTypeEntity Repository
  goodsTypeEntity: Repository<GoodsTypeEntity>;

  @InjectDataSource()
  defaultDataSource: DataSource; // 注入本地数据源

  @App()
  app: IMidwayApplication;

  @Inject()
  logger: ILogger;

  @Inject()
  oracleService: OracleService; // 注入封装的 Oracle 服务

  /**
   * 执行 Oracle 存储过程 (商品相关)
   * @param connection Oracle 连接
   * @param procedureName 存储过程名称
   * @param bindParams 绑定参数 (包含 yxc_b2b_goodsid)
   * @param taskId 任务 ID
   * @param logPrefix 日志前缀
   * @returns Promise<any[]> 结果数组
   */
  private async executeGoodsOracleProcedure(
    connection: oracledb.Connection,
    procedureName: string,
    bindParams: oracledb.BindParameters,
    taskId: string,
    logPrefix: string
  ): Promise<any[]> {
    this.logger.info(`[${taskId}] ${logPrefix} Calling SP ${procedureName}...`);
    const execOptions: oracledb.ExecuteOptions = {
      outFormat: oracledb.OUT_FORMAT_OBJECT,
      autoCommit: false // 假设存储过程主要是查询
    };
    try {
      // 注意商品存储过程的参数名是 :yxc_b2b_goodsid
      const result = await connection.execute<{ DATASET: oracledb.ResultSet<any> }>(
        `BEGIN ${procedureName}(:DATASET, :yxc_b2b_goodsid); END;`,
        bindParams,
        execOptions
      );

      this.logger.debug(`[${taskId}] ${logPrefix} SP ${procedureName} raw result outBinds:`, result.outBinds);

      if (result && result.outBinds && result.outBinds.DATASET) {
        const resultSet = result.outBinds.DATASET;
        if (resultSet && typeof resultSet.getRows === 'function') {
          const rows = await resultSet.getRows();
          await resultSet.close();
          this.logger.info(`[${taskId}] ${logPrefix} Fetched ${rows.length} rows from Oracle SP ${procedureName}.`);
          return rows;
        } else {
          this.logger.warn(`[${taskId}] ${logPrefix} SP ${procedureName} result did not contain a valid ResultSet in outBinds.DATASET. Value:`, resultSet);
          return [];
        }
      } else {
        this.logger.warn(`[${taskId}] ${logPrefix} SP ${procedureName} did not return expected outBinds or outBinds.DATASET.`);
        return [];
      }
    } catch (spError) {
      this.logger.error(`[${taskId}] ${logPrefix} Error executing SP ${procedureName}:`, spError);
      return [];
    }
  }

  /**
   * 同步所有商品相关数据 (Info, Price, Batch)
   * @param taskId 任务 ID
   */
  async syncAllGoodsData(taskId: string = 'manualSyncAllGoods') {
    this.logger.info(`[${taskId}] 开始执行商品数据同步任务 (Info, Price, Batch)...`);
    let totalGoodsToSync = 0;
    let processedGoods = 0;
    let infoUpdated = 0, infoInserted = 0;
    let priceUpdated = 0; // 统计价格更新次数
    let batchUpserted = 0; // 统计批次更新/插入数量

    const currentOracleDataSource = this.oracleService.getDataSource();
    if (!currentOracleDataSource || !currentOracleDataSource.isInitialized) {
      this.logger.error(`[${taskId}] Oracle 数据源 (via OracleService) 不可用或未初始化，任务中止。`);
      return;
    }

    let connection: oracledb.Connection | undefined;
    try {
      // 1. 获取 Oracle 连接
      this.logger.info(`[${taskId}] 获取 Oracle 连接 (从 DataSource 连接池)...`);
      const driver = currentOracleDataSource.driver as any;
      const pool = driver.pool || driver.master;
      if (!pool || typeof pool.getConnection !== 'function') {
        this.logger.error(`[${taskId}] 无法从 Oracle DataSource driver 获取连接池. Driver keys: ${Object.keys(driver).join(', ')}`);
        throw new Error('Could not obtain Oracle connection pool from TypeORM DataSource driver.');
      }
      connection = await pool.getConnection();
      this.logger.info(`[${taskId}] Oracle 连接获取成功.`);

      // 2. 查询需要同步的商品 ID 列表
      this.logger.info(`[${taskId}] 查询 YXC_B2B_INTERFACELIST 获取待同步商品ID...`);
      const goodsQuery = `SELECT DISTINCT RFID FROM YXC_B2B_INTERFACELIST WHERE INTERFACETYPE = 'GOODS' AND RFID IS NOT NULL`;
      const goodsResult = await connection.execute<{ RFID: string }>(goodsQuery, [], { outFormat: oracledb.OUT_FORMAT_OBJECT });

      const goodsIdsToSync = goodsResult.rows?.map(row => row.RFID) || [];
      totalGoodsToSync = goodsIdsToSync.length;
      this.logger.info(`[${taskId}] 从 YXC_B2B_INTERFACELIST 获取到 ${totalGoodsToSync} 个待同步的商品ID.`);

      if (totalGoodsToSync === 0) {
        this.logger.info(`[${taskId}] 没有需要同步的商品数据.`);
        return;
      }

      // --- 获取本地 GoodsInfo 映射 ---
      this.logger.info(`[${taskId}] 获取本地 GoodsInfo 映射...`);
      const localGoods = await this.goodsInfoEntity.find({ select: ['id', 'goodsId'] });
      const localGoodsMap = new Map(localGoods.map(g => [g.goodsId, { id: g.id }]));
      this.logger.info(`[${taskId}] 获取到 ${localGoodsMap.size} 个本地 GoodsInfo 记录.`);

      // 3. 遍历商品 ID，同步数据
      for (const goodsId of goodsIdsToSync) {
        processedGoods++;
        const logPrefix = `Goods ${goodsId} (${processedGoods}/${totalGoodsToSync}):`;
        this.logger.info(`[${taskId}] ${logPrefix} 开始处理...`);
        let goodsInfoProcessedSuccessfully = false;
        let currentLocalGoodsId: number | undefined = undefined;

        const existingLocalData = localGoodsMap.get(goodsId);
        if (existingLocalData) {
            currentLocalGoodsId = existingLocalData.id;
        }

        try {
          // --- 同步 GoodsInfo (基础信息) ---
          const goodsInfoParams: oracledb.BindParameters = {
            DATASET: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT },
            yxc_b2b_goodsid: { type: oracledb.STRING, dir: oracledb.BIND_IN, val: goodsId }
          };
          const oracleGoods = await this.executeGoodsOracleProcedure(connection, 'YXC_B2B_SPMX', goodsInfoParams, taskId, `${logPrefix} GoodsInfo`);

          if (!oracleGoods || oracleGoods.length === 0) {
            this.logger.warn(`[${taskId}] ${logPrefix} SP YXC_B2B_SPMX 未返回商品基础数据. 跳过此商品.`);
            continue; // 直接处理下一个商品
          }

          const oracleGood = oracleGoods[0];

          // --- 同步 Price --- (获取价格信息，但不立即更新)
          const goodsPriceParams: oracledb.BindParameters = {
            DATASET: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT },
            yxc_b2b_goodsid: { type: oracledb.STRING, dir: oracledb.BIND_IN, val: goodsId }
          };
          const oraclePrices = await this.executeGoodsOracleProcedure(connection, 'YXC_B2B_SPPRICE', goodsPriceParams, taskId, `${logPrefix} Price`);

          // --- 处理价格数据 ---
          const priceData: Partial<GoodsInfoEntity> = {};
          if (oraclePrices && oraclePrices.length > 0) {
              for (let i = 0; i < Math.min(oraclePrices.length, 4); i++) {
                 const priceLevel = oraclePrices[i];
                 priceData[`saleTaxPriceL${i + 1}`] = priceLevel.SALETAXP;
                 priceData[`salePriceL${i + 1}`] = priceLevel.SALEP;
                 if (i === 0) {
                    priceData.price = priceLevel.SALETAXP;
                 }
              }
              for (let i = oraclePrices.length; i < 4; i++) {
                  priceData[`saleTaxPriceL${i + 1}`] = 0; // 未返回的价格级别设为 0
                  priceData[`salePriceL${i + 1}`] = 0;   // 未返回的价格级别设为 0
              }
              this.logger.debug(`[${taskId}] ${logPrefix} 获取到 ${oraclePrices.length} 条价格数据.`);
          } else {
              this.logger.info(`[${taskId}] ${logPrefix} SP YXC_B2B_SPPRICE 未返回价格数据.`);
              priceData.price = 0;
              for (let i = 1; i <= 4; i++) {
                  priceData[`saleTaxPriceL${i}`] = 0;
                  priceData[`salePriceL${i}`] = 0;
              }
          }

          // --- 确定最终状态 (使用Oracle的ISSHOW字段) ---
          let finalStatus: number;
          if (oracleGood.ISSHOW !== undefined && oracleGood.ISSHOW !== null) {
              finalStatus = oracleGood.ISSHOW === 1 ? 1 : 0; // 直接使用Oracle的ISSHOW，1上架，0下架
              this.logger.debug(`[${taskId}] ${logPrefix} Status set to ${finalStatus} based on Oracle ISSHOW: ${oracleGood.ISSHOW}.`);
          } else {
              finalStatus = 0; // 如果ISSHOW为空，默认下架
              this.logger.debug(`[${taskId}] ${logPrefix} Status set to 0 (Oracle ISSHOW is null/undefined).`);
          }

          // --- 查找对应的商品类型ID ---
          let typeId: number | undefined;
          if (oracleGood.GCATEGORY) {
            const goodsType = await this.goodsTypeEntity.findOne({
              where: { gCategoryCode: oracleGood.GCATEGORY }
            });
            if (goodsType) {
              typeId = goodsType.id;
              this.logger.debug(`[${taskId}] ${logPrefix} 找到商品类型 ID: ${typeId} (gCategory: ${oracleGood.GCATEGORY})`);
            } else {
              this.logger.warn(`[${taskId}] ${logPrefix} 未找到对应的商品类型 (gCategory: ${oracleGood.GCATEGORY})`);
            }
          }

          // --- 准备合并的数据 (基础信息 + 价格信息 + 最终状态) ---
          const rawCombinedData: Partial<GoodsInfoEntity> = {
            // 基础信息映射
            goodsId: goodsId,
            title: oracleGood.GOODSNAME,
            entId: oracleGood.ENTID,
            goodsCode: oracleGood.GOODSCODE,
            oracleGoodsName: oracleGood.GOODSNAME,
            goodsSpec: oracleGood.GOODSSPEC,
            manufacturer: oracleGood.MANUFACTURER,
            unit: oracleGood.UNIT,
            approvalNo: oracleGood.APPROVALNO,
            formula: oracleGood.FORMULA,
            midpack: oracleGood.MIDPACK,
            qty: oracleGood.QTY,
            planCate: oracleGood.PLANCATE,
            logogram: oracleGood.LOGOGRAM,
            wholLimtNum: oracleGood.WHOLLIMTNUM,
            storNum: oracleGood.STORNUM,
            isMidpackSaleDisabled: oracleGood.ISMIDPACK,
            gCategory: oracleGood.GCATEGORY,
            qCategory: oracleGood.QCATEGORY,
            oracleIsHidden: oracleGood.ISSHOW,
            isPres: oracleGood.ISPRES === 'Y' ? 1 : 0,
            brandCode: oracleGood.BRAND_CODE,
            nextValPrice: oracleGood.NEXT_VAL_PRICE,
            // 合并价格数据
            ...priceData,
            // 设置最终状态
            status: finalStatus,
            // 设置商品类型ID
            typeId: typeId || 46
          };
          
          // 使用TrimUtil处理字符串字段，排除数值和布尔字段
          const combinedData = TrimUtil.trimObjectFields(rawCombinedData, [
            'midpack', 'qty', 'wholLimtNum', 'storNum', 'isMidpackSaleDisabled', 
            'oracleIsHidden', 'isPres', 'nextValPrice', 'price', 'status', 'typeId',
            'saleTaxPriceL1', 'salePriceL1', 'saleTaxPriceL2', 'salePriceL2',
            'saleTaxPriceL3', 'salePriceL3', 'saleTaxPriceL4', 'salePriceL4'
          ]);

          // --- 执行更新或插入 ---
          if (currentLocalGoodsId) {
            // 更新
            await this.goodsInfoEntity.update(currentLocalGoodsId, combinedData);
            infoUpdated++;
            if (Object.keys(priceData).length > 0) priceUpdated++; // 如果有价格数据被更新
            goodsInfoProcessedSuccessfully = true;
            this.logger.debug(`[${taskId}] ${logPrefix} GoodsInfo 更新 (ID: ${currentLocalGoodsId}).`);
          } else {
            // 查找对应的商品类型ID
            let typeId: number | undefined;
            if (oracleGood.GCATEGORY) {
              const goodsType = await this.goodsTypeEntity.findOne({
                where: { gCategoryCode: oracleGood.GCATEGORY }
              });
              if (goodsType) {
                typeId = goodsType.id;
                this.logger.debug(`[${taskId}] ${logPrefix} 找到商品类型 ID: ${typeId} (gCategory: ${oracleGood.GCATEGORY})`);
              } else {
                typeId = 46;
                this.logger.warn(`[${taskId}] ${logPrefix} 未找到对应的商品类型 (gCategory: ${oracleGood.GCATEGORY})`);
              }
            }

            // 插入
            combinedData.typeId = typeId; // 如果找不到对应的typeId，则为undefined
            const newGood = this.goodsInfoEntity.create(combinedData as GoodsInfoEntity);
            await this.goodsInfoEntity.save(newGood);
            currentLocalGoodsId = newGood.id;
            localGoodsMap.set(goodsId, { id: currentLocalGoodsId }); // 更新 Map
            infoInserted++;
            goodsInfoProcessedSuccessfully = true;
            this.logger.debug(`[${taskId}] ${logPrefix} GoodsInfo 新增 (New ID: ${currentLocalGoodsId}).`);
          }

          // --- 仅当 GoodsInfo 处理成功时，才同步 Batch ---
          if (goodsInfoProcessedSuccessfully && currentLocalGoodsId) {
            // --- 同步 Batch (先删后插) ---
            const goodsBatchParams: oracledb.BindParameters = {
              DATASET: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT },
              yxc_b2b_goodsid: { type: oracledb.STRING, dir: oracledb.BIND_IN, val: goodsId }
            };
            const oracleBatches = await this.executeGoodsOracleProcedure(connection, 'YXC_B2B_SP_BATCH', goodsBatchParams, taskId, `${logPrefix} Batch`);

            // 先删除旧批次
            this.logger.debug(`[${taskId}] ${logPrefix} Deleting existing batches for goodsId: ${goodsId}`);
            await this.goodsBatchEntity.delete({ goodsId: goodsId });

            if (oracleBatches && oracleBatches.length > 0) {
              // 对同一个goodsId的批次，只保留VALDATE最早的一条记录
              const batchMap = new Map<string, any>();
              
              oracleBatches.forEach(batch => {
                if (!batch.VALDATE) return; // 跳过没有有效期的批次
                
                const existingBatch = batchMap.get(goodsId);
                if (!existingBatch || new Date(batch.VALDATE) < new Date(existingBatch.VALDATE)) {
                  batchMap.set(goodsId, batch);
                }
              });

              const batchesToSave = [];
              let nearestExpiredDate: Date | null = null;

              for (const [_, batch] of batchMap) {
                const rawBatchData = {
                  goodsId: goodsId,
                  batchCode: batch.BATCHCODE,
                  valDate: batch.VALDATE,
                  stock: batch.STOCK || 0
                };
                // 使用TrimUtil处理字符串字段，排除日期和数值字段
                const trimmedBatchData = TrimUtil.trimObjectFields(rawBatchData, ['valDate', 'stock']);
                batchesToSave.push(this.goodsBatchEntity.create(trimmedBatchData));
                
                // 记录最早的有效期日期
                if (!nearestExpiredDate || new Date(batch.VALDATE) < nearestExpiredDate) {
                  nearestExpiredDate = new Date(batch.VALDATE);
                }
              }

              if (batchesToSave.length > 0) {
                await this.goodsBatchEntity.save(batchesToSave, { chunk: 50 });
                batchUpserted += batchesToSave.length;
                this.logger.debug(`[${taskId}] ${logPrefix} GoodsBatch 保存了 ${batchesToSave.length} 条批次记录（已去重保留最早有效期）.`);
              }

              // 更新商品信息的近效期字段
              if (nearestExpiredDate && currentLocalGoodsId) {
                await this.goodsInfoEntity.update(currentLocalGoodsId, { 
                  nearestExpiredDate: nearestExpiredDate 
                });
                this.logger.debug(`[${taskId}] ${logPrefix} 更新商品近效期日期: ${nearestExpiredDate.toISOString()}`);
              }
            } else {
              this.logger.info(`[${taskId}] ${logPrefix} SP YXC_B2B_SP_BATCH 未返回批次数据.`);
            }
          }

          this.logger.info(`[${taskId}] ${logPrefix} 处理完成.`);

          // 同步成功后，删除 YXC_B2B_INTERFACELIST 中对应记录
          const deleteSql = `DELETE FROM YXC_B2B_INTERFACELIST WHERE RFID = :rfid AND INTERFACETYPE = 'GOODS'`;
          await connection.execute(deleteSql, { rfid: goodsId }, { autoCommit: true });
          this.logger.info(`[${taskId}] ${logPrefix} 已从 YXC_B2B_INTERFACELIST 删除同步完成的商品记录.`);

        } catch (goodsError) {
          this.logger.error(`[${taskId}] ${logPrefix} 处理失败:`, goodsError);
        }
      }

      this.logger.info(`[${taskId}] 商品数据同步任务完成.`);
      this.logger.info(`    总计待同步商品: ${totalGoodsToSync}`);
      this.logger.info(`    成功处理商品: ${processedGoods}`);
      this.logger.info(`    GoodsInfo: 更新基础 ${infoUpdated} 条, 新增 ${infoInserted} 条`);
      this.logger.info(`    GoodsInfo: 更新价格 ${priceUpdated} 次`);
      this.logger.info(`    GoodsBatch: Upsert ${batchUpserted} 条 (按先删后插计算)`);

    } catch (error) {
      this.logger.error(`[${taskId}] 商品数据同步任务执行期间发生严重错误:`, error);
    } finally {
      // 6. 释放连接
      if (connection) {
        this.logger.info(`[${taskId}] 释放 Oracle 连接回连接池...`);
        try {
          await connection.close();
          this.logger.info(`[${taskId}] Oracle 连接已释放.`);
        } catch (releaseError) {
          this.logger.error(`[${taskId}] 释放 Oracle 连接时出错:`, releaseError);
        }
      }
    }
  }

  /**
   * 同步商品类型数据 (G Category)
   * @param taskId 任务 ID
   */
  async syncGoodsTypeData(taskId: string = 'manualSyncGoodsType') {
    this.logger.info(`[${taskId}] 开始执行商品类型(G Category)数据同步任务...`);
    let updatedCount = 0;
    let insertedCount = 0;

    const currentOracleDataSource = this.oracleService.getDataSource();
    if (!currentOracleDataSource || !currentOracleDataSource.isInitialized) {
      this.logger.error(`[${taskId}] Oracle 数据源不可用或未初始化，任务中止。`);
      return;
    }

    let connection: oracledb.Connection | undefined;
    try {
      // 1. 获取 Oracle 连接 (直接从 DataSource 获取)
      this.logger.info(`[${taskId}] 获取 Oracle 连接 (从 DataSource 连接池)...`);
      const driver = currentOracleDataSource.driver as any;
      const pool = driver.pool || driver.master;
      if (!pool || typeof pool.getConnection !== 'function') {
        this.logger.error(`[${taskId}] 无法从 Oracle DataSource driver 获取连接池. Driver keys: ${Object.keys(driver).join(', ')}`);
        throw new Error('Could not obtain Oracle connection pool from TypeORM DataSource driver.');
      }
      connection = await pool.getConnection();
      this.logger.info(`[${taskId}] Oracle 连接获取成功.`);

      // 2. 调用 YXC_B2B_GCATEGORY 存储过程
      this.logger.info(`[${taskId}] Calling SP YXC_B2B_GCATEGORY...`);
      const execOptions: oracledb.ExecuteOptions = {
        outFormat: oracledb.OUT_FORMAT_OBJECT
      };
      const bindParams: oracledb.BindParameters = {
        DATASET: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
      };
      // 这个 SP 只有输出参数，可以直接调用 execute
      const result = await connection.execute<{ DATASET: oracledb.ResultSet<any> }>(
        `BEGIN YXC_B2B_GCATEGORY(:DATASET); END;`,
        bindParams,
        execOptions
      );
 
      this.logger.info(`[${taskId}] SP YXC_B2B_GCATEGORY executed.`);

      let oracleTypes: any[] = [];
      if (result && result.outBinds && result.outBinds.DATASET) {
        const resultSet = result.outBinds.DATASET;
        if (resultSet && typeof resultSet.getRows === 'function') {
          oracleTypes = await resultSet.getRows();
          console.error(oracleTypes)
          await resultSet.close();
          this.logger.info(`[${taskId}] Fetched ${oracleTypes.length} types from Oracle SP.`);
        } else {
          this.logger.warn(`[${taskId}] SP result did not contain a valid ResultSet.`);
        }
      } else {
        this.logger.warn(`[${taskId}] SP did not return expected outBinds.`);
      }

      if (oracleTypes.length === 0) {
        this.logger.info(`[${taskId}] 从 Oracle 未获取到需要同步的商品类型数据.`);
        return; // 没有数据则直接结束
      }

      // 3. 获取本地所有商品类型用于比对
      this.logger.info(`[${taskId}] Fetching local goods types for comparison...`);
      const localTypes = await this.goodsTypeEntity.find();
      const localTypeMap = new Map(localTypes.map(t => [t.gCategoryCode, t]));
      this.logger.info(`[${taskId}] Found ${localTypeMap.size} local goods types.`);

      // 4. 遍历 Oracle 数据，进行更新或插入
      for (const oracleType of oracleTypes) {
        const [gCategoryCode, gCategoryName] = TrimUtil.trimMultiple(
          oracleType.GCATEGORYCODE, 
          oracleType.GCATEGORYNAME
        );

        if (!gCategoryCode) {
            this.logger.warn(`[${taskId}] Skipping Oracle record due to missing GCATEGORYCODE. Record:`, oracleType);
            continue; // 跳过没有 Code 的记录
        }

        const existingLocalType = localTypeMap.get(gCategoryCode);

        if (existingLocalType) {
          // 更新: 只更新 name 字段
          if (existingLocalType.name !== gCategoryName) {
            await this.goodsTypeEntity.update(existingLocalType.id, { name: gCategoryName });
            updatedCount++;
            this.logger.debug(`[${taskId}] GoodsType ${gCategoryCode} updated name to "${gCategoryName}".`);
          } else {
            // this.logger.debug(`[${taskId}] GoodsType ${gCategoryCode} name is already up-to-date.`);
          }
        } else {
          // 插入
          const newType = this.goodsTypeEntity.create({
            gCategoryCode: gCategoryCode,
            name: gCategoryName,
            // parentId, sortNum, pic, status 可以根据需要设置默认值或留空 (如果 nullable)
            status: 1 // 默认为启用状态
          });
          await this.goodsTypeEntity.save(newType);
          insertedCount++;
          this.logger.debug(`[${taskId}] GoodsType ${gCategoryCode} ("${gCategoryName}") inserted.`);
        }
      }

      this.logger.info(`[${taskId}] 商品类型同步任务完成. 更新: ${updatedCount} 条, 新增: ${insertedCount} 条.`);

    } catch (error) {
      this.logger.error(`[${taskId}] 商品类型同步任务执行失败:`, error);
    } finally {
      // 5. 释放连接
      if (connection) {
        this.logger.info(`[${taskId}] 释放 Oracle 连接...`);
        try {
          await connection.close();
          this.logger.info(`[${taskId}] Oracle 连接已释放.`);
        } catch (releaseError) {
          this.logger.error(`[${taskId}] 释放 Oracle 连接时出错:`, releaseError);
        }
      }
    }
  }

  /**
   * @deprecated 旧的同步方法，请使用 syncAllGoodsData
   */
  async syncGoodsData(taskId: string = 'manualSyncGoodsOnly', goodsId: string | null = null) {
    this.logger.warn(`[${taskId}] 调用了已废弃的 syncGoodsData 方法。请考虑使用 syncAllGoodsData。`);
    if (goodsId) {
        this.logger.warn(`[${taskId}] 单个商品同步 (${goodsId}) 在旧方法中不再支持，请使用新方法或修改.`);
    }
    this.logger.info(`[${taskId}] 旧的 syncGoodsData 方法执行完毕 (无实际操作).`);
  }
} 